<template>
  <!-- 可以手动添加数据的级联树 -->
  <div>
    <el-tree :data="data" node-key="id" default-expand-all :expand-on-click-node="false">
      <span class="hu-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button type="text" size="mini" @click="() => append(data)" icon="el-icon-plus" />
          <el-button
            type="text"
            size="mini"
            @click="() => remove(node, data)"
            icon="el-icon-delete"
          />
        </span>
      </span>
    </el-tree>
    <div>
      <el-button icon="el-icon-circle-plus-outline" type="text" @click="addTreeItem">添加父级</el-button>
    </div>
    <TreeNodeDialog ref="TreeNodeVisible" title="添加选项" @commit="appendNode" />
  </div>
</template>

<script>
import TreeNodeDialog from "./FGTreeNodeDialog.vue";

export default {
  components: {
    TreeNodeDialog,
  },
  model: {
    prop: "value", // 绑定的值，通过父组件传递
    event: "update",
  },
  props: {
    value: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      currentNode: null, // 当前节点
      data: JSON.parse(JSON.stringify(this.value)),
    };
  },

  methods: {
    append(data) {
      this.currentNode = data;
      this.addTreeItem();
    },

    remove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d) => d.id === data.id);
      children.splice(index, 1);
      this.$emit("update", this.data);
    },
    addTreeItem() {
      this.$refs.TreeNodeVisible.open();
    },
    // 添加子节点
    appendNode(node) {
      if (this.currentNode) {
        if (!this.currentNode.children) {
          data = Object.assign(this.currentNode, { "children": []})
        }
        this.currentNode.children.push(node);
        this.currentNode = null;
      } else {
        // 在根节点上添加节点
        this.data.push(node);
      }
      this.$emit("update", this.data);
    },
  },
};
</script>

<style lang="scss" >
.hu-tree-node {
  width: 100%;
  font-size: 14px;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  .node-operation {
    float: right;
  }
  i[class*="el-icon"] + i[class*="el-icon"] {
    margin-left: 6px;
  }
  .el-icon-delete {
    color: #157a0c;
  }
}
</style>
